package org.example.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.user.domain.Role;
import org.example.user.domain.RoleMenu;
import org.example.user.domain.UserRole;
import org.example.user.service.RoleMenuService;
import org.example.user.service.RoleService;
import org.example.user.mapper.RoleMapper;
import org.example.user.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author scf
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-05-21 20:01:05
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Override
    public List<Role> listAll(Role role) {
        return baseMapper.listAll(role);
    }

    @Override
    public Role getByUserId(Integer userId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,userId);
        UserRole one = userRoleService.getOne(wrapper);
        Role byId = this.getById(one.getRoleId());

        return byId;
    }

    @Override
    @Transactional
    public boolean updateRoleMenu(Role role) {
        Integer[] mids = role.getMids();
        boolean save =false;
        List<Integer> list = roleMenuService.getByRoleId(role.getId());
        for (Integer integer : list) {
            RoleMenu roleMenu = roleMenuService.getById(integer);
            save = roleMenuService.removeById(roleMenu);
        }
        for (Integer mid : mids) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(role.getId());
            roleMenu.setMenuId(mid);
             save = roleMenuService.save(roleMenu);
        }
        return save;
    }
}




